import { createRouter, createWebHashHistory } from "vue-router";
import layout from "@/views/layout/index.vue";
import home from "@/views/home/index.vue"
import useStore from "@/store";

const routes = [
  {
    path: "/",
    component: layout,
    children: [
      {
        path: "/",
        component: home,
      },
      {
        path: "/category/:id",
        component: () => import("@/views/category/index.vue"),
      },
      {
        path: "/category/sub/:id",
        component: () => import("@/views/category/sub.vue"),
      },
      {
        path: "goods/:id",
        component: () => import("@/views/goods/index.vue"),
      },
      {
        path: '/cart',
        component: () => import('@/views/cart/index.vue')
      },
      {
        path: '/member/checkout',
        component: () => import('@/views/member/pay/checkout.vue')
      },
      {
        path: '/member/pay',
        component: () => import('@/views/member/pay/index.vue')
      },
      {
        path: '/pay/callback',
        component: () => import('@/views/member/pay/callback.vue')
      },
      {
        path: '/member',
        component: () => import('@/views/member/layout/index.vue'),
        children: [
          {
            path: '',
            component: () => import('@/views/member/home/index.vue')
          },
          {
            path: 'order',
            component: () => import('@/views/member/order/index.vue')
          }
        ]
      }
    ]
  },
  {
    path: "/login",
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/login/callback",
    component: () => import("@/views/login/callback.vue"),
  },

]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 滚动行为
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition; // 返回之前保存的位置（前进/后退）
    } else if (to.hash) {
      // 如果有 hash 锚点，则滚动到指定元素
      return { el: to.hash, behavior: 'smooth' };
    } else {
      // 默认情况下滚动到页面顶部
      return { top: 0 };
    }
  }
})

router.beforeResolve((to, from, next) => {
  const { cartStore } = useStore()
  if (cartStore.isLogin) {
    // 已登录
    next()
  } else {
    // 未登录
    if (to.path.includes('/member')) {
      next({
        path: '/login',
        query: {
          redirectUrl: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router